<template>
  <view class="container" v-if="status">
    <map
      style="width: 100%; height: 100%"
      id="map"
      :longitude="longitude"
      :latitude="latitude"
      scale="14"
      show-location
      :bindregionchange="regionchange"
      :bindmarkertap="markertap"
      :markers="markers"
    ></map>
    <view class="address">{{ '您的位置：城建国际' + address }}</view>
  </view>
</template>

<script>
import { ref, onMounted, toRefs } from 'vue'

export default {
  setup() {
    const status = ref(false)
    const latitude = ref('')
    const longitude = ref('')
    const address = ref('')
    const markers = ref([
      {
        iconPath: '../logo.png',
        id: 0,
        latitude: 0,
        longitude: 0,
        width: 50,
        height: 50
      }
    ])

    const getLocation = () => {
      uni.getLocation({
        type: 'gcl84',
        success(res) {
          console.log(res.latitude)
          console.log(res.longitude)
          latitude.value = res.latitude
          longitude.value = res.longitude
          markers.value[0].longitude = res.longitude
          markers.value[0].latitude = res.latitude
        }
      })
    }

    const markertap = (e) => {
      console.log(e.markerId)
    }

    const regionchange = (e) => {
      if (e.type === 'end') {
        const mapCtx = uni.createMapContext('map')
        mapCtx.getCenterLocation({
          success: (res) => {
            markers.value[0].latitude = res.latitude
            markers.value[0].longitude = res.longitude
          }
        })
      }
    }

    onMounted(() => {
      status.value = true
      getLocation()
    })

    return {
      ...toRefs({
        latitude,
        longitude,
        address,
        markers
      }),
      status,
      markertap,
      regionchange
    }
  }
}
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  position: relative;
}
.address {
  position: absolute;
  bottom: 40rpx;
  width: 100%;
  padding: 20rpx;

  text-align: center;
}
</style>
